const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join("/")} ${[
    hour,
    minute,
    second,
  ]
    .map(formatNumber)
    .join(":")}`;
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

/***
 * @param icon string [success, error, loading, none]
 * */
const showToast = ({
  title, icon = "none", image = "", duration = 1500, mask = "false", success = () => {} }) =>{
  wx.showToast({
    title,
    duration,
    image,
    icon,
    mask,
    success,
  });
}
const showLoading = () => {
  if (!arguments.length) arguments[0] = { title: "正在加载", mask: false };
  wx.showLoading({ ...arguments[0] });
}
const hideLoading = () => {
  wx.hideLoading().catch((err) => err);
}
const showModal = ({content}) => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      content,
      success(res){
        res.confirm && resolve(res.confirm)
      }
    });
  });
}
function storage () {
  const setStorageSync = (key, value) => {
    wx.setStorageSync(key, JSON.stringify(value));
  };
  const getStorageSync = (key) => {
    const info = wx.getStorageSync(key) || "{}";
    return JSON.parse(info);
  };
  const removeStorageSync = (key) => {
    wx.removeStorageSync(key)
  };

  return {
    setStorageSync,
    getStorageSync,
    removeStorageSync
  }
}
/**
 * 
 * @param {*} object as ARRAY
 * @returns 空对象返回true 有值则返回false
 */
function isEmptyObject (object) {
  const OS = Object.prototype.toString;
  if ( OS.call(object) !== '[object Object]' && OS.call(object) !== '[object Array]') {
    throw "It's not an object"
  }
  return !Object.keys(object).length;
}
module.exports = {
  formatTime,
  showToast,
  showModal,
  showLoading,
  hideLoading,
  ...storage(),
  isEmptyObject
};
